<template>
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    :title="title"
    placement="right"
    @close="modalClose.close"
    @after-visible-change="afterVisibleChange"
  >
    <div>
      <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }" label-align="left" :layout="'vertical'">
        <a-form-item label="标识" v-bind="validateInfos.name">
          <a-input v-model:value="modelRef.name" :disabled="currentIndex !== -1" placeholder="请输入英文标识" />
        </a-form-item>
        <a-form-item label="名称" v-bind="validateInfos.label">
          <a-input v-model:value="modelRef.label" :disabled="isDetl" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="是否用户自定义">
          <a-switch v-model:checked="modelRef.customized" :disabled="isDetl" />
        </a-form-item>
        <a-form-item label="描述" v-bind="validateInfos.description">
          <a-textarea
            v-model:value="modelRef.description"
            placeholder="输入描述"
            :disabled="isDetl"
            :auto-size="{ minRows: 3, maxRows: 3 }"
          />
        </a-form-item>
        <a-form-item label="缩略图">
          <div style="position: relative; display: flex; width: 300px; height: 200px">
            <a-button v-show="!isDetl" style="position: absolute; top: -40px; left: 60px" @click="clickEntrEdit">
              进入设计
            </a-button>
            <img v-if="!reshowEdit" style="width: 100%; height: 100%" :src="modelRef.url" alt="" />
            <img v-else :src="modelRef.newImg" alt="" />
          </div>
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <div style="display: flex; justify-content: left">
        <div v-show="!isDetl">
          <a-button type="primary" @click="handleOk">{{ isDetl ? '关闭' : '确定' }}</a-button>
        </div>
        <div style="margin-left: 10px">
          <a-button @click="cancal">{{ isDetl ? '关闭' : '取消' }}</a-button>
        </div>
      </div>
    </template>
    <a-modal v-model:visible="modalClose.modalVisible" title="关闭" @ok="modalClose.modalHandleOk">
      <span>数据未保存,确认关闭吗?</span>
    </a-modal>
  </a-drawer>
</template>
<script>
import { defineComponent, ref, watch, defineEmits, toRefs, reactive, toRaw } from 'vue'
import { Form } from 'ant-design-vue'
import exp from '@/utils/regular'
import { setInitImg } from './transferFile'
const useForm = Form.useForm
import factory from '../factory'

export default defineComponent({
  props: {
    currentIndex: { type: Number, default: 0 },
    isShowEdit: { type: Boolean, default: false },
    menuList: {
      type: Object,
      default: () => {
        return {}
      },
    },
    oldmodelRef: {
      type: Object,
      default: () => {
        return {}
      },
    },
    isDetl: { type: Boolean, default: false },
    reshowEdit: { type: Boolean, default: false },
  },
  emits: ['closeEdit', 'createNewPage', 'clickEntrEdit', 'savePageSuccess'],
  setup(props, ctx) {
    const visible = ref(false)
    const { isShowEdit, menuList, currentIndex, oldmodelRef, isDetl, reshowEdit } = toRefs(props)
    const title = ref('')
    watch(isShowEdit, (newValue, oldValue) => {
      if (newValue) {
        visible.value = true
        title.value = currentIndex.value === -1 ? '新增页面' : '编辑页面'
        if (isDetl.value) {
          title.value = '详情'
        }
      }
    })

    /***表单*****************************/
    const modelRef = reactive({
      name: '',
      label: '',
      customized: false,
      description: '',
      smallImg: '',
    })
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: '请填入英文标识',
        },
        {
          pattern: exp.key.pattern,
          message: exp.key.message,
        },
        {
          max: 20,
          message: '最多输入20个字符',
        },
      ],
      label: [
        {
          required: true,
          message: '请输入名称',
        },
        {
          pattern: exp.name.pattern,
          message: exp.name.message,
        },
        {
          max: 25,
          message: '最多输入25个字符',
        },
      ],
      description: [
        {
          max: 127,
          message: '最多输入127个字符',
        },
      ],
    })
    const { validate, validateInfos } = useForm(modelRef, rulesRef, {
      //表单验证的输出: 字段 值 提示
      onValidate: (...args) => console.log('表单验证的输出: 字段 值 提示', ...args),
    })
    const onSubmit = () => {
      validate()
        .then(() => {
          //表单验证无误后执行
          saveToAliyun()
        })
        .catch((err) => {
          console.log('error', err)
        })
    }
    watch(visible, (newValue, oldValue) => {
      if (!newValue) {
        ctx.emit('closeEdit', false)
      } else if (reshowEdit.value) {
        //结束设计后第二次进入编辑页面
        for (let key in oldmodelRef.value) {
          modelRef[key] = oldmodelRef.value[key]
        }
        console.log('结束设计后第二次进入编辑页面', modelRef)
      } else if (currentIndex.value > -1) {
        let list = menuList.value[currentIndex.value]
        //获得单页面的布局与组件
        factory.getSinglePageInfo(list.id).then((res) => {
          //=========================
          for (let key in list) {
            modelRef[key] = list[key]
          }
          modelRef.layout = res.data.layout
          modelRef.portlets = res.data.portlets
          console.log('页面管理-编辑', modelRef, res)

          //备份数据
          modalClose.backupData = JSON.stringify(modelRef)
        })
      } else if (currentIndex.value === -1) {
        let obj = toRaw(modelRef)
        obj.id = ''
        obj.name = ''
        obj.label = ''
        obj.customized = false
        obj.description = ''
        obj.smallImg = ''
        obj.layout = []
        obj.portlets = []
        obj.modifyBy = ''
        obj.modifyTime = ''
        obj.img = ''
        obj.url = ''
        obj.newImg = ''
        obj.createBy = ''
        obj.customized = false

        //备份数据
        modalClose.backupData = JSON.stringify(modelRef)
      }
    })
    //==页脚按钮=================
    const handleOk = (e) => {
      if (!isDetl.value) {
        onSubmit()
      } else {
        cancal()
      }
    }
    const cancal = () => {
      modalClose.close()
    }
    const clickEntrEdit = () => {
      ctx.emit('clickEntrEdit', modelRef)
    }

    /*****************************/
    const saveToAliyun = () => {
      if (reshowEdit.value) {
        let img64 = modelRef.newImg.replace('data:image/jpeg;base64,', '')
        let fileList = dataURLtoFile(img64, 'portal-' + modelRef.name + '.png')
        let fileList2
        setInitImg(modelRef.url, (file) => {
          fileList2 = file
        })

        factory.getALiYunInfo().then((obj) => {
          obj.key = obj.dir + fileList.name
          modelRef.img = obj.key
          let fd = new FormData()
          fd.append('name', fileList.name)
          fd.append('key', obj.key)
          fd.append('policy', obj.policy)
          fd.append('OSSAccessKeyId', obj.accessId)
          fd.append('success_action_status', '200')
          fd.append('signature', obj.signature)
          // fd.append("callback", obj.callback)
          fd.append('file', fileList)
          factory.uploadImg(obj.host, fd).then((res) => {
            //测试,写死resourcePath
            modelRef.resourcePath = '/test/img/p1.png' + Date.parse(new Date())
            if (currentIndex.value === -1) {
              factory.savePage({ ...modelRef, newImg: '' }).then((res) => {
                visible.value = false
                ctx.emit('savePageSuccess', '')
              })
            } else {
              factory
                .updatePage({ ...modelRef, newImg: '' })
                .then((res) => {
                  visible.value = false
                  ctx.emit('savePageSuccess', '')
                })
                .catch((err) => {
                  //更新失败了,要把原来的缩略图重写上传给 OSS
                  console.log('更新失败了,要把原来的缩略图重写上传给 OSS', modelRef)
                  fd.set('file', fileList2)
                  factory.uploadImg(obj.host, fd).then((res) => {})
                })
            }
          })
        })
      } else {
        factory.updatePage(modelRef).then((res) => {
          visible.value = false
          ctx.emit('savePageSuccess', '')
        })
      }
    }

    function dataURLtoFile(dataurl, filename) {
      var mime = 'image/jpg',
        bstr = atob(dataurl),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    }

    //==确认关闭对话框======================
    const modalClose = reactive({
      backupData: '',
      close: (e) => {
        if (JSON.stringify(modelRef) !== modalClose.backupData) {
          visible.value = true
          modalClose.modalVisible = true
          return
        }
        visible.value = false
      },
      modalVisible: false,
      modalHandleOk: () => {
        visible.value = false
        modalClose.modalVisible = false
      },
    })

    return {
      title,
      visible,
      handleOk,
      cancal,
      clickEntrEdit,
      validateInfos,
      modelRef,
      modalClose,
    }
  },
})
</script>
